<template>
  <div class="control-panel">
    <el-container>
      <el-header>
        <div class="header-content">
          <h1>数据大屏远程控制面板</h1>
          <div class="connection-status">
            <el-tag :type="screenStore.isConnected ? 'success' : 'danger'">
              {{ screenStore.isConnected ? '已连接' : '未连接' }}
            </el-tag>
            <span class="last-update">最后更新: {{ screenStore.lastUpdate || '无' }}</span>
          </div>
        </div>
      </el-header>
      
      <el-main>
        <el-row :gutter="20">
          <!-- 模式控制 -->
          <el-col :span="12">
            <el-card class="control-card">
              <template #header>
                <div class="card-header">
                  <span>切换模式控制</span>
                </div>
              </template>
              
              <el-radio-group v-model="screenStore.config.mode" @change="handleModeChange">
                <el-radio label="auto">自动切换</el-radio>
                <el-radio label="manual">手动切换</el-radio>
              </el-radio-group>
              
              <div class="mode-description">
                <p v-if="screenStore.config.mode === 'auto'">
                  自动模式：系统将按照设定的时间间隔自动切换页面
                </p>
                <p v-else>
                  手动模式：需要手动点击页面名称进行切换
                </p>
              </div>
            </el-card>
          </el-col>
          
          <!-- 间隔时间控制 -->
          <el-col :span="12">
            <el-card class="control-card">
              <template #header>
                <div class="card-header">
                  <span>自动切换间隔时间</span>
                </div>
              </template>
              
              <el-slider
                v-model="screenStore.config.interval"
                :min="5"
                :max="60"
                :step="5"
                show-input
                :disabled="screenStore.config.mode === 'manual'"
                @change="handleIntervalChange"
              />
              <div class="interval-description">
                <p>当前间隔: {{ screenStore.config.interval }} 秒</p>
                <p v-if="screenStore.config.mode === 'manual'" class="disabled-text">
                  手动模式下间隔时间设置无效
                </p>
              </div>
            </el-card>
          </el-col>
        </el-row>
        
        <!-- 页面切换控制 -->
        <el-card class="control-card page-control">
          <template #header>
            <div class="card-header">
              <span>页面切换控制</span>
            </div>
          </template>
          
          <div class="page-grid">
            <el-button
              v-for="page in screenStore.config.pages"
              :key="page"
              :type="screenStore.config.currentPage === page ? 'primary' : 'default'"
              size="large"
              @click="handlePageSwitch(page)"
              class="page-button"
            >
              {{ page }}
            </el-button>
          </div>
          
          <div class="current-page-info">
            <p>当前页面: <strong>{{ screenStore.config.currentPage }}</strong></p>
          </div>
        </el-card>
        
        <!-- 实时状态显示 -->
        <el-card class="control-card">
          <template #header>
            <div class="card-header">
              <span>实时状态</span>
            </div>
          </template>
          
          <el-descriptions :column="2" border>
            <el-descriptions-item label="当前模式">
              {{ screenStore.config.mode === 'auto' ? '自动切换' : '手动切换' }}
            </el-descriptions-item>
            <el-descriptions-item label="切换间隔">
              {{ screenStore.config.interval }} 秒
            </el-descriptions-item>
            <el-descriptions-item label="当前页面">
              {{ screenStore.config.currentPage }}
            </el-descriptions-item>
            <el-descriptions-item label="连接状态">
              <el-tag :type="screenStore.isConnected ? 'success' : 'danger'">
                {{ screenStore.isConnected ? '已连接' : '未连接' }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>

        <!-- 页面访问链接 -->
        <el-card class="control-card">
          <template #header>
            <div class="card-header">
              <span>页面访问</span>
            </div>
          </template>
          
          <div class="page-links">
            <el-button 
              type="primary" 
              size="large"
              @click="openInNewTab('/pagescreen')"
              icon="Monitor"
            >
              单页面大屏
            </el-button>
            <el-button 
              type="success" 
              size="large"
              @click="openInNewTab('/screen')"
              icon="Connection"
            >
              路由大屏
            </el-button>
          </div>
          
          <div class="link-description">
            <p><strong>单页面大屏</strong>: 单页面切换模式，适合传统大屏展示</p>
            <p><strong>路由大屏</strong>: 多路由页面模式，支持远程路由切换</p>
          </div>
        </el-card>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import { onMounted, onUnmounted } from 'vue'
import { useScreenStore } from '../stores/screenStore'
import WebSocketService from '../utils/websocket'
import { ElMessage } from 'element-plus'

export default {
  name: 'ControlPanel',
  setup() {
    const screenStore = useScreenStore()
    
    // 连接WebSocket
    const connectWebSocket = async () => {
      try {
        await WebSocketService.connect()
        screenStore.isConnected = true
        
        // 订阅配置更新
        WebSocketService.subscribe('/topic/screen-config', (message) => {
          if (message.type === 'config') {
            Object.assign(screenStore.config, message.data)
            screenStore.lastUpdate = message.timestamp
            ElMessage.success('配置已更新')
          }
        })
        
        // 订阅页面切换
        WebSocketService.subscribe('/topic/screen-switch', (message) => {
          if (message.type === 'switch') {
            screenStore.config.currentPage = message.data
            screenStore.lastUpdate = message.timestamp
            ElMessage.success(`页面已切换到: ${message.data}`)
          }
        })
        
        // 获取初始配置
        await screenStore.fetchConfig()
        
      } catch (error) {
        console.error('WebSocket连接失败:', error)
        ElMessage.error('连接失败，请检查服务器状态')
        screenStore.isConnected = false
      }
    }
    
    // 处理模式切换
    const handleModeChange = async (mode) => {
      try {
        await screenStore.setMode(mode)
        ElMessage.success(`模式已切换到: ${mode === 'auto' ? '自动' : '手动'}`)
      } catch (error) {
        ElMessage.error('模式切换失败')
      }
    }
    
    // 处理间隔时间变化
    const handleIntervalChange = async (interval) => {
      try {
        await screenStore.setInterval(interval)
        ElMessage.success(`间隔时间已设置为: ${interval}秒`)
      } catch (error) {
        ElMessage.error('间隔时间设置失败')
      }
    }
    
    // 处理页面切换
    const handlePageSwitch = async (pageName) => {
      try {
        await screenStore.switchPage(pageName)
        ElMessage.success(`页面已切换到: ${pageName}`)
      } catch (error) {
        ElMessage.error('页面切换失败')
      }
    }

    // 在新标签页打开页面
    const openInNewTab = (path) => {
      window.open(path, '_blank')
    }
    
    onMounted(() => {
      connectWebSocket()
    })
    
    onUnmounted(() => {
      WebSocketService.disconnect()
    })
    
    return {
      screenStore,
      handleModeChange,
      handleIntervalChange,
      handlePageSwitch,
      openInNewTab
    }
  }
}
</script>

<style scoped>
.control-panel {
  height: 100vh;
  background: #f0f2f5;
}

.el-header {
  background: #fff;
  border-bottom: 1px solid #e4e7ed;
  padding: 0 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
}

.header-content h1 {
  margin: 0;
  color: #303133;
  font-size: 24px;
}

.connection-status {
  display: flex;
  align-items: center;
  gap: 15px;
}

.last-update {
  color: #909399;
  font-size: 14px;
}

.el-main {
  padding: 20px;
}

.control-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.mode-description,
.interval-description {
  margin-top: 15px;
  color: #606266;
  font-size: 14px;
}

.disabled-text {
  color: #c0c4cc;
  font-style: italic;
}

.page-control {
  margin-top: 20px;
}

.page-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 15px;
  margin-bottom: 20px;
}

.page-button {
  height: 60px;
  font-size: 16px;
}

.current-page-info {
  text-align: center;
  padding: 15px;
  background: #f5f7fa;
  border-radius: 4px;
}

.current-page-info p {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.current-page-info strong {
  color: #409eff;
}

.page-links {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.link-description {
  color: #606266;
  font-size: 14px;
}

.link-description p {
  margin: 8px 0;
}
</style> 